"""
知识库管理接口
"""
from pathlib import Path
from fastapi import APIRouter, HTTPException
from app.models.response import (
    KnowledgeStatusResponse,
    DocumentListResponse,
    DocumentInfo,
    DeleteDocumentResponse
)
from app.storage.json_storage import KnowledgeBaseStorage
from app.core.config import settings

router = APIRouter()


def get_storage() -> KnowledgeBaseStorage:
    """获取存储实例"""
    return KnowledgeBaseStorage(
        storage_path=settings.knowledge_base_path,
        embedding_model=settings.EMBEDDING_MODEL
    )


@router.get("/status", response_model=KnowledgeStatusResponse)
async def get_knowledge_status():
    """
    获取知识库状态
    
    返回知识库的基本信息，包括文档数、文本块数、总字符数等
    """
    try:
        storage = get_storage()
        status = storage.get_status()
        
        return KnowledgeStatusResponse(**status)
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取状态时发生错误: {str(e)}")


@router.get("/documents", response_model=DocumentListResponse)
async def list_documents():
    """
    获取已上传的文档列表
    
    返回所有文档的详细信息
    """
    try:
        storage = get_storage()
        documents = storage.get_document_list()
        
        doc_info_list = [
            DocumentInfo(
                filename=doc["filename"],
                upload_time=doc["upload_time"],
                file_size=doc["file_size"],
                chunk_count=doc["chunk_count"],
                total_characters=doc["total_characters"]
            )
            for doc in documents
        ]
        
        return DocumentListResponse(
            documents=doc_info_list,
            total=len(doc_info_list)
        )
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取文档列表时发生错误: {str(e)}")


@router.delete("/document/{filename}", response_model=DeleteDocumentResponse)
async def delete_document(filename: str):
    """
    删除指定文档
    
    - **filename**: 要删除的文档文件名
    
    删除内容包括：
    - data/uploads/ 目录下的原始文件
    - knowledge_base.json 中该文档的所有文本块和元数据
    """
    try:
        storage = get_storage()
        
        # 从知识库删除文档数据
        result = storage.delete_document(filename)
        
        if not result:
            raise HTTPException(status_code=404, detail=f"文档 '{filename}' 不存在")
        
        # 删除原始文件
        file_path = settings.uploads_dir / filename
        if file_path.exists():
            file_path.unlink()
        
        return DeleteDocumentResponse(
            status="success",
            filename=result["filename"],
            deleted_chunks=result["deleted_chunks"]
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除文档时发生错误: {str(e)}")

